<!--
 * @Author: Xujianchen
 * @Date: 2024-12-23 14:59:48
 * @LastEditors: xujianchen
 * @LastEditTime: 2024-12-23 15:55:06
 * @Description: better-scroll 上拉加载
-->
<template>
  <Wrapper>
    <div class="pullup">
      <div
        ref="wrapperRef"
        class="pullup-wrapper"
      >
        <div class="pullup-content">
          <ul class="pullup-list">
            <li
              v-for="i of data"
              :key="i"
              class="pullup-list-item"
            >
              {{ i % 5 === 0 ? 'scroll up 👆🏻' : `I am item ${i} ` }}
            </li>
          </ul>
          <div class="pullup-tips">
            <div
              v-if="!isPullUpLoad"
              class="before-trigger"
            >
              <span class="pullup-txt">上拉加载更多</span>
            </div>
            <div
              v-else
              class="after-trigger"
            >
              <span class="pullup-txt">加载中...</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Wrapper>
</template>

<script setup>
import BScroll from '@better-scroll/core'
import Pullup from '@better-scroll/pull-up'

BScroll.use(Pullup)

const bscroll = ref(null)
const wrapperRef = ref(null)
const isPullUpLoad = ref(false)
const data = ref(30)

onMounted(() => initBScroll())

function initBScroll() {
  const bs = (bscroll.value = new BScroll(wrapperRef.value, {
    pullUpLoad: true,
  }))
  bs.on('pullingUp', pullingUpHandler)
}

async function pullingUpHandler() {
  isPullUpLoad.value = true
  await requestData()
  const bs = bscroll.value
  bs.finishPullUp()
  bs.refresh()
  isPullUpLoad.value = false
}

async function requestData() {
  try {
    const newData = await ajaxGet()
    data.value += newData
  } catch (err) {
    console.log(err)
  }
}
function ajaxGet() {
  return new Promise((resolve) => {
    setTimeout(() => resolve(20), 1000)
  })
}
</script>

<style scoped lang="scss">
.pullup {
  height: 500px;

  &-wrapper {
    height: 100%;
    padding: 0 $space-small-s;
    border: 1px solid #ccc;
    overflow: hidden;
  }

  &-list {
    padding: 0;
  }

  &-list-item {
    padding: $space-small-s 0;
    list-style: none;
    border-bottom: 1px solid #ccc;
  }

  &-tips {
    padding: $space-medium-s;
    text-align: center;
    color: #999;
  }
}
</style>
